package onework;

import javax.swing.*;
import java.awt.*;

public class Main {
    private static TeachingManagementSystemGUI gui;

    public static void main(String[] args) {
        try {
            // 测试数据库连接
            if (!MySQL.testConnection()) {
                JOptionPane.showMessageDialog(null,
                        "无法连接到数据库，请检查数据库配置和服务是否启动。",
                        "数据库连接错误",
                        JOptionPane.ERROR_MESSAGE);
                System.exit(1);
            }

            // 加载数据
            MySQL.loadAllData();

            // 启动GUI界面
            SwingUtilities.invokeLater(() -> {
                gui = new TeachingManagementSystemGUI();
                gui.setVisible(true);

                // 设置关闭窗口时的操作
                gui.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                gui.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                        try {
                            // 保存数据
                            MySQL.saveAllData();
                            System.out.println("数据已保存");
                            // 退出程序
                            System.exit(0);
                        } catch (Exception e) {
                            e.printStackTrace();
                            JOptionPane.showMessageDialog(gui,
                                    "保存数据时出错：" + e.getMessage(),
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                    }
                });
            });

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null,
                    "程序启动错误：" + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}